<?php
/**
 * Created by PhpStorm.
 * User: yys
 * Date: 2016/12/2
 * Time: 10:16
 */

namespace App\Services\ProductTempService;


use Illuminate\Support\Facades\DB;

class ProductTempAttributeService
{
    static function getTempAttributesByClassId($product_category_id){
        if(empty($product_category_id)||!is_int($product_category_id)){
            return array();
        }
        $temp_attributes= DB::table('product_temp_attributes')->where(array('state'=>1,'category_id'=>$product_category_id))
            ->select('attr_id','category_id','attr_name','attr_type','attr_values')
            ->get()
            ->toArray();
        foreach ($temp_attributes as $attribute){
            $attr_value_arr=explode('|',$attribute->attr_values);
            if(sizeof($attr_value_arr)>1){
                $attr_value_arr=array_filter($attr_value_arr);
            }
            $attribute->attr_values=empty($attr_value_arr)?array():$attr_value_arr;
        }
        return $temp_attributes;
    }

    /***
     * 获取产品模板已选属性
     * @param $product_temp_id
     * @return mixed
     */
    static function getTempAttrsByProductTempId($product_temp_id){
        $product_temp_id=trim($product_temp_id);
        $temp_attr_maps= DB::table('product_temp_attr_maps')->where(array('state'=>1,'product_temp_id'=>$product_temp_id))
            ->get()
            ->toArray();
        return $temp_attr_maps;
    }
    /***
     * 获取一条产品属性
     * @param $id
     * @return null
     */
    static function getTempAttributeById($attr_id){
        if(!is_int($attr_id)){
            return null;
        }
        $temp_attribute= DB::table('product_temp_attributes')->where(array('state'=>1,'attr_id'=>$attr_id))
            ->first();
        return $temp_attribute;
    }

    /***
     * 查看属性类型名是不是已经存在
     * @param $attr_id
     * @param $category_id
     * @param $attr_name
     * @param int $state
     * @return bool
     */
    public static function tempAttNameExistsByCategoryIdAndName($attr_id,$category_id,$attr_name,$state=1){
        if(empty($category_id)||empty($attr_name)){
        return false;
        }
         $query=DB::table('product_temp_attributes')->where(array('category_id'=>$category_id,'attr_name'=>$attr_name));
        if($state===1){
            $query->where('state',1);
        }
        if(!empty($attr_id)){
            $query->where('attr_id','<>',$attr_id);
        }
        $num=$query->count();
        return ($num>0)?true:false;
    }
}